package jp.co.jbuy.util;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

/**
 * DESで暗号化するクラス（復号化可能）
 * 
 * @author songyx
 */
public class DES {

	private SecretKey secretKey;

	public String encryptDes(String clearText) throws NoSuchAlgorithmException,
			NoSuchPaddingException, InvalidKeyException,
			IllegalBlockSizeException, BadPaddingException {

		KeyGenerator keyGen = KeyGenerator.getInstance("DES");
		secretKey = keyGen.generateKey();
		keyGen.init(56);

		byte[] clearTextByte = clearText.getBytes();

		Cipher cipher = Cipher.getInstance("DES");
		cipher.init(Cipher.ENCRYPT_MODE, secretKey);

		byte[] encryptedBytes = cipher.doFinal(clearTextByte);
		String encryptedHexString = BinaryHexConverter
				.bytesToHexString(encryptedBytes);

		return encryptedHexString;
	}

	public String decryptDes(String encryptedHexText)
			throws NoSuchAlgorithmException, NoSuchPaddingException,
			InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

		Cipher cipher = Cipher.getInstance("DES");
		cipher.init(Cipher.DECRYPT_MODE, secretKey);

		byte[] decryptedByte = cipher.doFinal(BinaryHexConverter
				.HexStringToBytes(encryptedHexText));
		String decryptedText = new String(decryptedByte);

		return decryptedText;
	}

}
